/**
 * 过滤视图
 * 包括分页(paging)、过滤(filtering)
 */

define(['jquery', 'underscore', 'backbone', 'RootView'],
    function ($, _, Backbone, RootView) {
        var filterView = RootView.extend({
            el: 'body',
            events: {
                'click                                       .filter-select a': 'filtering',
                'changeDate          .filter-select[type="date"]  .datepicker': 'filtering',
                'change                                        .filter :radio': 'filtering',
                'change                                        .filter select': 'filtering',
                'submit                                          .filter form': 'filtering',
                'mouseover                         .filter-select[type="tag"]': 'highlightTag',
                'mouseout                          .filter-select[type="tag"]': 'downplayTag',
                'click                                     .pagination      a': 'paging',
                'change                                  .paginations  select': 'paging',
                'keyup                                    .paginations  input': 'paging',
                'focus                                    .filter-range input': 'toggleRangeOK',
                'click                                      .sort .sort-field': 'sorting',
                'click                        .operate-select .operate-option': 'operating',
                'click                                [data-trigger="filter"]': 'executeFilter'
            },
            initialize: function () {
                this.resetParams();
                $('.filter-select[type="tag"] .selected').each(function(){
                    var tagBg = $(this).data('tag-bg');
                    $(this).css('background', tagBg);
                    $(this).css('color', '#fff');
                    $(this).css('border-color', tagBg);
                });
            },
            executeFilter: function (event) {
                var $target = $(event.target),
                    $targetFilter = $($target.data('target'));
                this.destoryModal($target.closest('.modal'));
                this.filter($targetFilter);
            },
            //# tag高亮
            highlightTag: function (event) {
                var $target = $(event.target),
                    tagBg = $target.data('tag-bg');
                if (!$target.hasClass('selected')) {
                    $target.css('background', tagBg);
                    $target.css('color', '#fff');
                    $target.css('border-color', tagBg);
                }
            },
            //# tag还原
            //
            downplayTag: function (event) {
                var $target = $(event.target);
                if (!$target.hasClass('selected')) {
                    $target.css('background', '#fff');
                    $target.css('color', '#76838f');
                    $target.css('border-color', '#dee5e8');
                }
            },
            //# 过滤区间确认按钮toggle
            //
            toggleRangeOK: function (event) {
                var $target = $(event.target),
                    $filterRange = $target.closest('.filter-range'),
                    $rangeOk = $filterRange.find('button');

                $rangeOk.show();

            },
            //# 生成过滤参数
            //
            generateParams: function () {
                var params = {};
                _.extend(params, this.pagingParams);
                _.extend(params, this.generateFilterParams());
                return params;
            },
            //# 重置过滤参数
            //
            resetParams: function () {
                this.pagingParams = {
                    'pageIndex': 1,
                    'pageSize': 10
                };

                this.filteringParams = {};

                this.sortParams = {};

                this.sortParams = {};
            },

            /**
             * 根据filter中条件筛选
             * @param $filter
             *        筛选条件的filter
             */
            filter: function ($filter) {
                var successMode = $filter.data('success-mode');

                switch (successMode) {
                    case 'refresh':
                        var $refreshTarget = $($filter.data('refresh-target'));
                        this.refresh($refreshTarget, this.generateParams());
                }

            },
            //执行筛选
            filtering: function (event) {
                event.preventDefault();
                var $target = $(event.target),
                    $filter = $target.closest('.filter'),
                    $select = $target.closest('.filter-select'),
                    nodeName = event.currentTarget.nodeName,
                    that = this;

                if ($select.attr('type') == 'tag') {
                    $target.toggleClass('selected');
                    if ($target.hasClass('selected')) {
                        that.highlightTag(event);
                    } else {
                        that.downplayTag(event);
                    }
                }

                if ($select.attr('type') == 'date') {
                    if (nodeName == 'A') {
                        $select.find('a').removeClass('selected');
                        $select.find('input').val('');
                        $target.addClass('selected');
                    }

                    if (nodeName == "INPUT") {
                        $target.datepicker('hide');
                        $select.find('a').removeClass('selected');
                    }

                }
                this.filter($filter);
            },

            /**
             * 构建过滤参数
             * @returns {{}|*|params}
             */
            generateFilterParams: function () {
                this.resetParams();

                var params = this.filteringParams;

                //tag选择值
                this.$('.filter .filter-select[type="tag"]').each(function () {
                    var $select = $(this).closest('.filter-select');
                    var key = $select.data('name'),
                        value = [];
                    $select.find('a.selected').each(function () {
                        var $option = $(this);
                        value.push($option.data('value'));

                    });
                    params[key] = value;
                });

                //日期选择值
                this.$('.filter .filter-select[type="date"]').each(function () {
                    var $select = $(this).closest('.filter-select');
                    var key = $select.data('name'),
                        value = null;
                    if ($select.find('a.selected').length > 0) {
                        value = $select.find('a.selected').data('value');
                        params[key] = value;
                    } else {
                        $select.find('.datepicker').each(function () {
                            var datekey = $(this).attr('name'),
                                datevalue = $(this).val();
                            //date[datekey] = datevalue;
                            params[datekey] = datevalue;
                        });
                    }
                });

                //checkbox选中值
                this.$('.filter :checkbox:checked').each(function () {
                    var key = $(this).attr('name'),
                        value = $(this).val();
                    params[key] = value;
                });

                //radio选中值
                this.$('.filter :radio:checked').each(function () {
                    var key = $(this).attr('name'),
                        value = $(this).val();
                    params[key] = value;
                });

                //输入框值
                this.$('.filter input[type="text"],.filter input[type="hidden"]').each(function () {
                    var key = $(this).attr('name'),
                        value = $(this).val();
                    params[key] = value;
                });

                //select 值
                this.$('.filter select').each(function () {
                    var key = $(this).attr('name'),
                        value = $(this).val();
                    params[key] = value;
                });

                this.filteringParams = params;
                return params;
            },

            /**
             * 分页操作
             * @param event
             *
             */
            paging: function (event) {
                event.preventDefault();

                var $target = $(event.currentTarget),
                    $paginations = $target.closest('.paginations'),
                    $pageSize = $paginations.find('select'),
                    nodeName = event.target.nodeName,
                    pageSizeName = $pageSize.attr('name'),
                    pageIndexName = $paginations.data('name');

                var index = this.pagingParams.pageIndex;

                switch (nodeName) {
                    case 'A':
                        index = $target.closest('li').data('value') || 0;
                        break;
                    case 'INPUT':
                        if (event.keyCode != 13) {
                            return;
                        } else {
                            if ($target.val() <= 1) {
                                index = 1;
                            } else {
                                index = $target.val() - 1;
                            }
                        }
                        break;
                    default:
                        break;
                }

                this.pagingParams[pageIndexName] = index;
                this.pagingParams[pageSizeName] = $pageSize.val();

                this.filter($paginations);
            },

            //# 排序
            //
            sorting: function (event) {
                var $target = $(event.target),
                    $sortArrow = $target.next('.sort-arrow'),
                    sortby = $target.data('sortby'),
                    successMode = $target.data('success-mode');

                if ($sortArrow.hasClass('asc')) {
                    this.sortParams[sortby] = 'desc';
                    $sortArrow.addClass('desc');
                    $sortArrow.removeClass('asc');
                } else {
                    this.sortParams[sortby] = 'asc';
                    $sortArrow.removeClass('desc');
                    $sortArrow.addClass('asc');
                }

                if (successMode == 'refresh') {
                    this.refresh($($target.data('refresh-target')), _.extend(this.sortParams, this.generateParams()));
                }

            },

            operating: function (event) {
                event.preventDefault();
                var $target = $(event.target),
                    $targetSelect = $target.closest('.operate-select'),
                    $targetOption = $target.closest('.operate-option'),
                    that = this;

                if ($targetOption.hasClass('return')) {
                    $('.filter').show();
                } else {
                    $('.filter').hide();
                }

                var $operateInput = $('<input id="OperateFilter" type="hidden"/>');
                if ($('.filter').find('#OperateFilter').length == 0) {
                    $operateInput.attr('name', $targetSelect.data('name'));
                    $operateInput.val($targetOption.data('value'));
                    $('.filter').append($operateInput);
                } else {
                    $('.filter').find('#OperateFilter').val($targetOption.data('value'));
                }


                that.filter($('.filter'));
            }

        });
        return filterView;
    });
